<?php
/*
    OpenLib
    Copyright (C) 2011  Michael Gukov, Pham Thi Thuy Duong

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

namespace App\Controllers;

use Sun\Sun;
use Sun\Validators;
use Sun\Utils;
use Sun\Html;
use App\Models;

class Dbase extends \Sun\Controller {
    public function __construct() {
        parent::__construct("Main");
    }
    public function MainAction($req) {
        header("Location: ?p=Index\\Enter");
    }

    public function UploadAction($req) {

        $page = new Html\HtmlPage("LoadFile");
        $script = new Html\Script();
        $page->Head()->Add($script);

        $messages = array(
            400 => "Не удалось загрузить файл",
            401 => "Размер файла не должен превышать 20 Мб"
        );

        try {
            $max_file_size = (int)Sun::conf("data/max_file_size");
            $file = current($_FILES);

            if ($file['size'] > $max_file_size)
                throw new \Sun\Exception("BigFileSize", 401);

            $file_type = substr($file['name'], strrpos($file['name'], "."));
            $uniname = Utils::RandomString(20).$file_type;
            $path = "pub/data/load/".$uniname;

            if (move_uploaded_file($file['tmp_name'], $path)) {
                $db = new Models\DB();
                $query = "INSERT INTO file(path, uniname, name)
                    VALUES('{$path}', '{$uniname}', '{$file['name']}')";
                $db->SafeExec($query);

                $script->script = "Response = {
                    status: 0,
                    file: \"{$file['name']}\",
                    name: \"{$uniname}\",
                    file_id: \"{$db->lastInsertId("file_id")}\" };";

            } else throw new \Sun\Exception("ErrorCopyFile", 400);

        } catch(\Sun\Exception $e) {
            $script->script = "Response = {
                status: {$e->getCode()},
                err_msg: \"{$messages[$e->getCode()]}\"}";
        }
        echo $page->ToHtml();
    }
}

